package cn.by.wms.service;

import cn.by.wms.dao.OutItemDao;
import cn.by.wms.dao.OutMasterDao;
import cn.by.wms.dto.InventoryOptionDTO;
import cn.by.wms.entity.OutItem;
import cn.by.wms.entity.OutMaster;
import cn.by.wms.entity.OutMasterQuery;
import cn.by.wms.event.InventoryOptionEvent;
import cn.hutool.core.date.DateUtil;
import cn.smart.core.util.UserSessionContext;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 出库单头;(206_out_master)表服务实现类
 *
 * @author : heimi
 * @date : 2024-12-2
 */
@Service
public class OutMasterService {

    @Autowired
    private OutMasterDao outMasterDao;
    @Autowired
    private OutItemDao outItemDao;
    @Autowired
    private ApplicationEventPublisher publisher;

    public List<OutMaster> select(OutMasterQuery query) {
        return outMasterDao.select(query);
    }

    public Integer insert(OutMaster outMaster) {
        //生成出库单的Id
        String outId = "Out" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS");
        outMaster.setId(outId);
        //为明细插入outId和最后更新人
        List<OutItem> outItems = outMaster.getOutItems();
        outItems.forEach(ioItem -> {
            ioItem.setOutId(outId);
            ioItem.setLastUpdateBy(UserSessionContext.get().getNickName());
        });
        //执行事务插入
        OutMasterService outMasterService = (OutMasterService) (AopContext.currentProxy());
        outMasterService.addOut(outMaster);
        return 0;
    }

    @Transactional
    public void addOut(OutMaster outMaster) {
        outMasterDao.insert(outMaster);
        outItemDao.insertBatch(outMaster.getOutItems());
        //进行库存操作
        InventoryOptionDTO inventoryOptionDTO = new InventoryOptionDTO().setOptionType("out").setRefId(outMaster.getId());
        InventoryOptionEvent inventoryOptionEvent = new InventoryOptionEvent(inventoryOptionDTO);
        publisher.publishEvent(inventoryOptionEvent);
    }

    public Integer update(OutMaster outMaster) {
        return outMasterDao.update(outMaster);
    }

    public Integer delete(Integer id) {
        return outMasterDao.delete(id);
    }


}